#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""文件上传服务器
使用FastAPI框架创建一个高性能的HTTP服务器，用于接收文件上传请求
"""

import os
import uuid
import json
from datetime import datetime
from fastapi import FastAPI, File, UploadFile, Form, HTTPException, Response
from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles
from fastapi.middleware.cors import CORSMiddleware
from src.ai import ask_ai
from src.image_converter import convert_to_jpg





# 获取项目根目录的绝对路径
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_DIR = os.path.join(BASE_DIR, 'static')

# 创建FastAPI应用
app = FastAPI(
    title="OCR RPA Auto Form",
    description="OCR + RPA自动填表系统：识别图片中的表单信息并自动填充到网页表单中",
    version="0.1.0",
    docs_url="/docs",
    redoc_url="/redoc"
)

# 设置上传文件保存目录
UPLOAD_FOLDER = os.path.join(STATIC_DIR, 'uploads')
# 确保上传目录存在
os.makedirs(UPLOAD_FOLDER, exist_ok=True)

# 配置CORS中间件，允许所有来源访问
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 挂载静态文件目录
app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")

# 确保API文档路由正常工作
app.openapi_url = "/openapi.json"


@app.post("/upload")
async def upload_file(file: UploadFile = File(...), input_xpath: str = Form(None)) -> Response:
    """处理文件上传请求"""
    try:
        # 检查文件名是否为空
        if not file.filename:
            raise HTTPException(status_code=400, detail="未选择文件")

        print(f'input_xpath: {input_xpath}')
        # 生成唯一的文件名，避免文件名冲突
        unique_id = str(uuid.uuid4())[:8]
        timestamp = datetime.now().strftime('%Y%m%d%H%M%S')
        file_extension = os.path.splitext(file.filename)[1]
        new_filename = f"{timestamp}_{unique_id}{file_extension}"

        # 保存文件到上传目录
        file_path = os.path.join(UPLOAD_FOLDER, new_filename)
        
        # 读取文件内容并保存
        content = await file.read()
        with open(file_path, "wb") as f:
            f.write(content)

        # 转换为jpg
        file_path_jpg = convert_to_jpg(file_path, width=1400)
        
        return file_path_jpg
        
        # 调用AI处理并直接返回结果（恢复原始业务逻辑）
        res = ask_ai(file_path_jpg,hint)
        print(f'模型输出: {res}')
        # 返回纯文本响应，不让FastAPI进行JSON包装
        return Response(content=res, media_type="text/plain")

    except Exception as e:
        # 记录错误信息
        print(f"上传文件时出错: {str(e)}")
        # 错误情况也返回纯文本
        error_text = f'{{"error": "上传文件时出错: {str(e)}"}}'
        return Response(content=error_text, media_type="text/plain", status_code=500)


@app.get("/")
async def index():
    """根路由，返回static目录中的index.html"""
    return FileResponse(os.path.join(STATIC_DIR, 'index.html'))

@app.get("/index_div")
async def index_div():
    """根路由，返回static目录中的index_div.html"""
    return FileResponse(os.path.join(STATIC_DIR, 'index_div.html'))

if __name__ == '__main__':
    import uvicorn
    # 启动服务器，监听所有地址的5656端口
    # 当直接运行时，不使用reload以避免模块导入问题
    uvicorn.run(app, host='0.0.0.0', port=5657, reload=False)
